import org.w3c.dom.Node;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2024-08-01
 * Time: 13:33
 */
public class SingleLinkedList {
    static class ListNode{
        public int val;
        public ListNode next;
        ListNode(int val){
            this.val=val;
        }
    }
    public ListNode head;
    public SingleLinkedList(){
        ListNode node1=new ListNode(10);
        ListNode node2=new ListNode(20);
        ListNode node3=new ListNode(30);
        ListNode node4=new ListNode(40);
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        this.head=node1;
    }
    //头插法
    public void addFirst(int val){
        ListNode node=new ListNode(val);
        node.next=head;
        head=node;
    }
    //尾插法
    public void addLast(int val){
        ListNode node=new ListNode(val);
        if(head==null){
            head=node;
            return;
        }
        ListNode cur=head;
        while(cur.next!=null){
            cur=cur.next;
        }
        cur.next=node;
    }
    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index,int val){
        ListNode node =new ListNode(val);
        ListNode cur =head;
        if(index<0||index>size()){
            System.out.println("下标不合法");
        }
        if (index==0){
            addFirst(val);
        }
        if(index==size()){
            addLast(val);
        }
        for (int i = 0; i < index-1; i++) {
            cur=cur.next;
        }
        node.next=cur.next;
        cur.next=node;
    }
    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key){
        ListNode cur=head;
        while (cur.next!=null){
            if(cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }
    //删除第一次出现关键字为key的节点
    public void remove(int key){
        ListNode cur=head;
        if (head.val == key) {
            head = head.next;
            return;
        }
        while (cur.next!=null){
            if(cur.next.val==key){
                break;
            }
            cur=cur.next;
        }
        cur.next=cur.next.next;
    }
    //删除所有值为key的节点
    public void removeAllKey(int key){
        ListNode cur=head;
        while (cur.next!=null){
            if(cur.next.val==key){
                cur.next=cur.next.next;
            }else{
                cur=cur.next;
            }
        }
        if (head.val==key){
            head=head.next;
        }
    }
    public int size(){
        ListNode cur=head;
        int count=0;
        while(cur.next!=null){
            cur=cur.next;
            count++;
        }
        return count;
    }
    public void display(){
        ListNode cur=head;
        while (cur!=null){
            System.out.print(cur.val+" ");
            cur=cur.next;
        }
        System.out.println();
    }
    public void clear() {
        head = null;
    }

}
